﻿using FinMath;
using FinModel;
using FinPricing;
using FinTrade;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FinStrategy
{
    public class DeltaHedgeStrategy : Strategy
    {
        public override void Execute(Portfolio portfolio, ExecuteContext context)
        {
            var option = portfolio.Positions.Single(p => p.Instrument is Option).Instrument as Option;
            var trade = CreateTrade(context, portfolio, option);

            OrderTrade(context, portfolio, trade);
            UpdatePosition(context, portfolio, trade);
        }

        private void UpdatePosition(ExecuteContext context, Portfolio portfolio, Trade trade)
        {
            portfolio[trade.Instrument].Quantity += trade.Quantity;
        }

        private Trade OrderTrade(ExecuteContext context, Portfolio portfolio, Trade trade)
        {
            context.Trading.Order(new Trade[] { trade }, new TradeContext());

            return trade;
        }

        private Trade CreateTrade(ExecuteContext context, Portfolio portfolio, Option option)
        {
            var price = context.MarketData[option.Underlying].Price;
            var delta = context.Risking.RiskIt(option, context.MarketData).Delta;
            var t = FMath.T((DateTime.Now - option.StartDate).TotalDays);

            var thePosition = portfolio[option];
            var underlyingPosition = portfolio[option.Underlying];

            return new Trade()
            {
                Instrument = option.Underlying,
                Quantity = delta * thePosition.Quantity / price - underlyingPosition.Quantity,
                Price = price,
                TS = DateTime.Now,
                Type = TradeType.BuyLong
            };
        }
    }
}
